package jude.java.util;

import java.util.HashMap;
import java.util.Map;

/**
 * 计数
 */
public final class I {
	public static final String TOTAL = "total";
	public static final String SUCCESS = "success";
	public static final String FAIL = "fail";
	public static final String ERROR = "error";
	public static final String FOUND = "found";
	
	private int i;
	
	private static Map<String, I> IS = new HashMap<String, I>();
	
	public int getI() {
		return i;
	}
	
	public int val() {
		return i;
	}
	
	public I increase() {
		next();
		return this;
	}
	
	public synchronized int next() {
		return ++i;
	}
	
	@Override
	public int hashCode() {
		return i;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (!(obj instanceof I))
			return false;
		return i == ((I)obj).i;
	}
	
	@Override
	public String toString() {
		return Integer.toString(i);
	}

	public static I get(String name) {
		I i = IS.get(name);
		if (i != null)
			return i;
		i = new I();
		IS.put(name, i);
		return i;
	}
	
	public static void reset(String name) {
		IS.remove(name);
	}
	
	public static void resetAll() {
		IS.clear();
	}
	
	public static I total() {
		return get(TOTAL).increase();
	}
	
	public static I success() {
		return get(SUCCESS).increase();
	}
	
	public static I fail() {
		return get(FAIL).increase();
	}
	
	public static I error() {
		return get(ERROR).increase();
	}
	
	public static I found() {
		return get(FOUND).increase();
	}
	
	public static String stat() {
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, I> e : IS.entrySet()) {
			sb.append(e.getKey()).append("\t---- ").append(e.getValue()).append("\n");
		}
		return sb.toString();
	}
}
